package com.codingapi.auto.deploy.email;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author modificial
 * @date 2018/7/24
 * @company codingApi
 * @description
 */
@Component
public class MailUtils {
    private static  final Logger logger = LoggerFactory.getLogger(MailUtils.class);

    @Autowired
   private JavaMailSender mailSender;

    public  boolean sendHtmlEmail(String deliver, String[] receiver, String[] carbonCopy, String subject, String content, boolean isHtml) {
        long startTimestamp = System.currentTimeMillis();
        logger.info("Start send email ...");
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message);
            messageHelper.setFrom(deliver);
            messageHelper.setTo(receiver);
            messageHelper.setCc(carbonCopy);
            messageHelper.setSubject(subject);
            messageHelper.setText(content, isHtml);
            mailSender.send(message);
            logger.info("Send email success, cost {} million seconds", System.currentTimeMillis() - startTimestamp);
            logger.info("发送成功");
            return true;
        } catch (MessagingException e) {
            logger.error("Send email failed, error message is {}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }
}
